package com.bw.zg2.viewmodel

import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import com.bw.zg2.base.BaseResult
import com.bw.zg2.base.BaseViewModel
import com.bw.zg2.bean.LoginBean
import com.bw.zg2.http.HttpUtil
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.MutableSharedFlow
import kotlinx.coroutines.flow.asSharedFlow
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.flow.flowOn
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext

/**
 *
 * @ClassName: LoginViewModel
 * @Description: java类作用描述
 * @Author: zhangyanchao
 * @CreateDate: 2024/9/12 11:55 AM
 * @Version: 1.0
 */
class LoginViewModel : BaseViewModel() {

    val loginLiveData = MutableLiveData<BaseResult<LoginBean>>()

    fun login(map: Map<String, String>) {
        // 发送网络请求，实现登录
        viewModelScope.launch(Dispatchers.IO) {
            //开启一个协程
            //切换至子线程
            //viewModelScope viewModel的协程作用域
            loginLiveData.postValue(
                apiService.login(map)
            )
        }

//        viewModelScope.launch() {
//            //开启一个协程
//            //viewModelScope viewModel的协程作用域
//            withContext(Dispatchers.IO){
//                loginLiveData.postValue(
//                    HttpUtil.apiService.login(map)
//                )
//            }
//        }

    }

    private val _loginSharedFlow = MutableSharedFlow<BaseResult<LoginBean>>()
    val loginSharedFlow = _loginSharedFlow.asSharedFlow()
    fun loginFlow(map: Map<String, String>) {
        viewModelScope.launch() {
            _loginSharedFlow.emit(HttpUtil.apiService.login(map))
        }
    }




}